<?php
namespace Commons;

class Cookie
{
    /**
     * 设置cookie，并且对不为空的域名进行加密
     * 请注意有效时间,单位秒,无须加上当前时间
     *
     * @param string $key      cookie的键
     * @param string $value    cookie的值
     * @param int    $expire   过期时间,单位秒,请注意这里不需要加上当前时间
     * @param string $path     存储的路径
     * @param string $domain   域名
     * @param bool   $secure   是否需要https connection
     * @param bool   $httpOnly 是否只有通过http协议
     *
     * @return bool
     */
    public function set($key, $value, $expire = 0, $path = '/', $domain = '', $secure = false, $httpOnly = false)
    {
        $expire = time() + $expire;
        if ($value != '') {
            $crypt = new MyCrypt();
            return setcookie($key, $crypt->encrypt($value), $expire, $path, $domain, $secure, $httpOnly);
        }
        return setcookie($key, $value, $expire, $path, $domain, $secure, $httpOnly);
    }

    /**
     * 获取cookie
     *
     * @param $key
     *
     * @return string
     */
    public function get($key)
    {
        if (isset($_COOKIE[$key])) {
            $v = $_COOKIE[$key];
            if ($v != '') {
                $crypt = new MyCrypt();
                return $crypt->decrypt($v);
            }
        }
        return '';
    }

    /**
     * 删除cookie
     *
     * @param $key
     *
     * @return bool
     */
    public function delete($key)
    {
        return $this->set($key, '', -1);
    }

    /**
     * 清空cookie
     */
    public function flush()
    {
        $cookieKeys = isset($_COOKIE) ? $_COOKIE : '';
        foreach ($cookieKeys as $k => $v) {
            $this->delete($k);
        }
    }
}
